package com.ruoyi.auth.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.auth.service.FusionLoginService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.domain.dto.pack.AliFusionDto;
import com.ruoyi.common.core.domain.vo.AliPhoneVo;
import com.ruoyi.common.core.utils.AliPhoneUtil;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.system.api.model.LoginUser;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author: Wuzh
 * @date: 2025-03-13 18:14
 * @description:
 */
@Tag (name = "认证 - 融合登录")
@RestController
@Slf4j
public class FusionLoginController {

    @Resource
    private FusionLoginService fusionLoginService;
    @Resource
    private TokenService tokenService;

    @GetMapping ("/getToken")
    @Operation (summary = "通过阿里完成融合登录")
    public AjaxResult getAppInfo (@RequestBody AliFusionDto aliPhoneVerifyTokenReq) {
        try {
            //1.获取Token
            AliPhoneVo token = AliPhoneUtil.getToken (aliPhoneVerifyTokenReq);
            return AjaxResult.success ( token.getModel () );
        } catch ( Exception e ) {
            e.printStackTrace ();
        }
        return null;
    }


    /**
     * 融合登录，APP一键认证，如果失败则自动跳转到短信验证码
     * @param aliPhoneVerifyTokenReq
     * @return
     */
    @PostMapping ("/verify")
    @Operation (summary = "通过APP的VerifyToken获取手机号")
    public R verify (@RequestBody AliFusionDto aliPhoneVerifyTokenReq) {
        try {
            AliPhoneVo aliPhoneBo = AliPhoneUtil.verifyToken ( aliPhoneVerifyTokenReq );
//             拿到数据进行登录
             String model = aliPhoneBo.getModel ();
             JSONObject jsonObject = JSONObject.parseObject ( model );
             String phoneNumber = (String) jsonObject.get ( "phoneNumber" );
//            String phoneNumber = "18005699662";
            LoginUser authLoginRespVO = fusionLoginService.fusionLogin ( phoneNumber, aliPhoneVerifyTokenReq.getBundleId () );
            Map<String, Object> token = tokenService.createToken ( authLoginRespVO );
            authLoginRespVO.setToken ( (String) token.get ( "access_token" ) );
            authLoginRespVO.setExpireTime ( (Long) token.get ( "expires_in" ) );
            return R.ok ( authLoginRespVO );
        } catch ( Exception e ) {
            e.printStackTrace ();
        }
        return null;
    }
}
